﻿using System;
using System.Web;
using WAD.WEB.AppCode;
using WAD.Model;
using WAD.DAL;
using WAD.BLL;
using System.Collections.Generic;
using WAD.Client2.WXPay;

namespace WAD.WEB.Client2.Ajax
{
    /// <summary>
    /// 发财：分享主 提现接口
    /// </summary>
    public partial class FC_Cash : AjaxBase
    {
        public override void AjaxMethodDispatch(String identity)
        {
            switch (identity)
            {
                case "add": this.Add(); break;
            }
        }
        static object lockObj = new object();
        /// <summary>
        /// 申请提现
        /// </summary>
        [QD.Web.Ajax.AjaxMethod]
        public void Add()
        {
            IsLogin();
            MFCCash m = GetModel();
            if (m.amount < 50)
                JsonResult(11, "提现金额必需大于50元");


            MUser mUser = DaoUser.GetEntity(UserId);
            if (String.IsNullOrEmpty(mUser.phone) || !mUser.is_validate_phone)
            {
                //没有验证手机号,不允许提现
                JsonResult(Message.Code.NO_VALIDATE_PHONE, Message.Msg.NO_VALIDATE_PHONE);
            }

            decimal balance = 0;
            int type = Parse.Int("type", 2);   //1 广告主提现, 2 分享主提现

            if (m.platform == 2)
            {
                Dictionary<string, object> setting = DAOFCSetting.Get("fc_setting", "user_id=" + m.user_id, "");
                if (setting == null)
                    JsonResult(11, "请完善设置后再提现");

                if (string.IsNullOrEmpty(Convert.ToString(setting["ali_name"])))
                    JsonResult(11, "请设置您的支付宝账号");

                if (string.IsNullOrEmpty(Convert.ToString(setting["ali_truename"])))
                    JsonResult(11, "请设置您的支付宝姓名");

                //if (Convert.ToString(setting["state"]) != "1")
                //{
                //    JsonResult(11, "您的个人信息未审核");
                //}
            }


            //余额>提现金额，允许添加提现申请
            Dictionary<string, object> user = DaoUser.GetDetail(m.user_id, "ad_balance,shared_balance,is_validate_phone");

            if (Convert.ToInt32(user["is_validate_phone"]) != 1)
                JsonResult(11, "手机号未验证不能提现");


            if (DAOFCShared.GetCount_No(m.user_id) > 0)
                JsonResult(11, "有红包被拒绝，重新上传后才能提现");

            if (type == 1)
                balance = DaoUser.BalanceDncode(user["ad_balance"], WJXConfig.EncryptConfig.DES_KEY);
            else
            {
                type = 2;
                balance = DaoUser.BalanceDncode(user["shared_balance"], WJXConfig.EncryptConfig.DES_KEY);
            }

            if (balance < m.amount)
                JsonResult(11, "系统余额不足");

            bool isErr = false;
            int count = 0, count2 = 0;
            lock (lockObj)
            {
                m.orderid = FCOrderBLL.CreateId(m.user_id);
                try
                {
                    //广告主提现，添加广告主交易记录
                    if (type == 1)
                        m.record_id = AddRecord(m.user_id, m.amount, (balance - m.amount));

                    //添加提现申请
                    count = DAOFCCash.Add(m);
                    if (count > 0)
                        count2 = DaoUser.UpdateBalance(m.user_id, (balance - m.amount), type);  //扣除余额
                }
                catch { isErr = true; }

                //系统报错,回滚
                if (isErr)
                {
                    //回滚广告主记录
                    if (m.record_id > 0)
                        DAOFCRecord.Delete(m.record_id);

                    //回滚申请记录
                    if (count > 0)
                        DAOFCCash.Delete(m.user_id, m.orderid);

                    //回滚余额
                    if (count2 > 0)
                        DaoUser.UpdateBalance(m.user_id, (balance - m.amount), type);
                }
            }

            if (count > 0)
                Success();
            Fail();
        }

        //添加广告主交易记录
        int AddRecord(int user_id, decimal amount, decimal balance)
        {
            MFCRecord re = new MFCRecord();
            re.user_id = user_id;
            re.amount = amount * -1;
            re.direction = 2;   //扣费
            re.balance = balance;
            re.article_id = 0;
            re.date = DateTime.Now;
            re.ip = Request.UserHostAddress;
            re.orderid = 0;
            re.remark = "";
            return DAOFCRecord.Add_Return(re);
        }

        MFCCash GetModel()
        {
            MFCCash m = new MFCCash()
            {
                user_id = Parse.Int("user_id", 0),
                amount = Parse.Decimal("amount", 0),
                platform = Parse.Int("platform", 1),
                
                callback_msg = "",
                state = 0,
                record_id = 0,
                check_date = null,
                check_adminid = 0,
                date = DateTime.Now,
                wx_appid=WxPayConfig.APPID,
                wx_mchid = WxPayConfig.MCHID
            };
            var user=DaoUser.GetEntity(m.user_id);
            m.openid = user.wx_login_openid;
            m.nickname = user.nick_name;
            return m;
        }
    }
}